import click
from pathlib import Path
from . import settings as setting


class QuecPyPI(click.MultiCommand):

    def list_commands(self, ctx):
        rv = []
        for path in Path(setting.CMD_FOLDER).iterdir():
            if path.suffix == '.py' and path.name != '__init__.py':
                rv.append(path.stem)
        rv.sort()
        return rv

    def get_command(self, ctx, cmd):
        ns = {}

        file = Path(setting.CMD_FOLDER, cmd + '.py')
        if not file.exists():
            return

        with file.open(mode='r') as f:
            code = compile(f.read(), file.name, 'exec')
            eval(code, ns, ns)

        for _, command in ns.items():
            if isinstance(command, click.Command) and command.name == cmd:
                return command


def print_settings(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return

    settings = ctx.obj['settings']
    for k, v in settings.__dict__.items():
        if k.startswith('__') or k.islower():
            continue
        click.secho('{}: {}'.format(k, v), fg='cyan')
    ctx.exit()


@click.command(cls=QuecPyPI,
               help='This tool\'s subcommands are loaded from a '
                    'plugin folder dynamically.',
               context_settings={
                   'obj': {'settings': setting}
               })
@click.version_option(prog_name='QuecPyPI',
                      version='1.0')
@click.option('--settings',
              is_flag=True,
              expose_value=False,
              callback=print_settings,
              help='Show settings and exit.',
              is_eager=True)
def cli():
    pass
